package pkg

import (
	"fmt"
	"os"
	"short-link/configs"

	"github.com/spf13/viper"
)

var Config *configs.Config

func LoadConfig() *configs.Config {

	path, err := os.Getwd() // get current path
	if err != nil {
		panic(err)
	}

	viper.SetConfigName("application-" + environment())
	viper.SetConfigType("yaml")
	viper.AddConfigPath(path + "/configs") // path to look for the config file in

	if err := viper.ReadInConfig(); err != nil { // Handle errors reading the config file
		panic(fmt.Errorf("fatal error config file: %w", err))
	}

	config := &configs.Config{}
	if err := viper.Unmarshal(config); err != nil {
		panic(err)
	}

	return config
}

func ReadConfig() *configs.Config {
	Config = LoadConfig()
	return Config
}

func environment() string {

	// get current path
	path, err := os.Getwd()
	if err != nil {
		panic(err)
	}

	// set for the config file
	viper.SetConfigName("application")
	viper.SetConfigType("yaml")
	viper.AddConfigPath(path + "/configs")

	// read config
	if err := viper.ReadInConfig(); err != nil { // Handle errors reading the config file
		panic(fmt.Errorf("fatal error config file: %w", err))
	}
	profile := &configs.Profile{}
	if err := viper.Unmarshal(profile); err != nil {
		panic(err)
	}

	// return environment
	return profile.Env
}
